package com.roubsite.cloud.common.utils;

import com.roubsite.cloud.common.service.RedisService;
import lombok.Getter;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtil implements ApplicationContextAware {

	//获取applicationContext
	@Getter
	private static ApplicationContext applicationContext;
	@Autowired
	RedisService redisService;

	/**
	 * 验证验证码是否匹配
	 *
	 * @param captchaCode 验证码
	 * @param captchakey  header的captcha值
	 * @return true 通过 false 校验不通过
	 */
	public boolean verifyCode(String captchaCode, String captchakey) {
		Object obj = redisService.getFromRedis("captcha" + captchakey);
		redisService.delFromRedis("captcha" + captchakey);
		if (ObjectUtils.isNotEmpty(obj)) {
			String redisCode = obj.toString().toUpperCase();
			return StringUtils.equalsAnyIgnoreCase(redisCode, captchaCode);
		}
		return false;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if (SpringUtil.applicationContext == null) {
			SpringUtil.applicationContext = applicationContext;
		}
	}

}

